#!/bin/ash
#
# CXL WITH FSDAX

# DETECT CXL TOPOLOGY
CMDLINE=$(cat /proc/cmdline)
CXL_TOPOLOGY=$(echo "${CMDLINE}" | grep -o 'BiscuitOS_CXL_TPG_[^ ]*')

# BUILD SPECIFY DEVDAX
if [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_0" ]; then
	echo "BiscuitOS CXL TYPE3: x0 Switch and x1 PMEM"

	# CXL SETUP
	cxl destroy-region -f all
	cxl create-region -d decoder0.0 -m mem0 -s 512M -t pmem -w 1 -g 4096 -u
	cxl enable-region region0

	# NDCTL LIST
	ndctl destroy-namespace --force all
	ndctl enable-region region0
	# BUILD DEVDAX ON /dev/pmem0
	ndctl create-namespace --mode=fsdax -f

elif [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_1" ]; then
	echo "BiscuitOS CXL TYPE3: x0 Switch and x1 DDR"

	echo "CXL VOLATILE MEMORY DOESN'T SUPPORT FSDAX"
	exit 0

elif [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_2" ]; then
	echo "BiscuitOS CXL TYPE3: x1 Switch and x1 PMEM"

	# CXL SETUP
	cxl destroy-region -f all
	cxl create-region -d decoder0.0 -m mem0 -s 512M -t pmem -w 1 -g 4096 -u
	cxl enable-region region0

	# NDCTL LIST
	ndctl destroy-namespace --force all
	ndctl enable-region region0
	# BUILD DEVDAX ON /dev/pmem
	ndctl create-namespace --mode=fsdax -f

elif [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_3" ]; then
	echo "BiscuitOS CXL TYPE3: x1 Switch and x1 DDR"

	echo "CXL VOLATILE MEMORY DOESN'T SUPPORT FSDAX"
	exit 0

elif [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_4" ]; then
	echo "BiscuitOS CXL TYPE3: x3 Switch and x8 DDR"

	echo "CXL VOLATILE MEMORY DOESN'T SUPPORT FSDAX"
	exit 0

elif [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_5" ]; then
	echo "BiscuitOS CXL TYPE3: x3 Switch and x8 PMEM"

	# CXL SETUP
	cxl destroy-region -f all
	cxl create-region -d decoder0.0 -m mem0 -s 512M -t pmem -w 1 -g 4096 -u
	cxl enable-region region0

	# NDCTL LIST
	ndctl destroy-namespace --force all
	ndctl enable-region region0
	# BUILD DEVDAX ON /dev/pmem0
	ndctl create-namespace --mode=fsdax -f

elif [ ${CXL_TOPOLOGY} = "BiscuitOS_CXL_TPG_6" ]; then
	echo "BiscuitOS CXL TYPE3: x3 Switch and x4 DDR/PMEM"

	echo "CXL VOLATILE MEMORY DOESN'T SUPPORT FSDAX"
	exit 0

fi

# BUILD FSDAX FILESYSTEM
mkfs.ext4 -b 4096 -E stride=512 -F /dev/pmem0
mkdir -p /mnt/DAX
mount -o dax=always,lazytime /dev/pmem0 /mnt/DAX/
echo "Aello BiscuitOS" > /mnt/DAX/BiscuitOS.txt
echo ""

# ALLOC FROM FSDAX
BiscuitOS-CXL-FSDAX-default
